package com.atung.merchant.config.security;

import java.net.InetAddress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.net.UnknownHostException;
import java.util.Optional;
/**
 * @author Administrator
 */
@Slf4j
public class WebIpUtil {

    private static final String IP_UNKNOWN = "unknown";
    private static final String IP_LOCAL = "127.0.0.1";
    private static final String IPV6_LOCAL = "0:0:0:0:0:0:0:1";
    private static final int IP_LEN = 15;
    /**
     * 获取用户真实IP地址，不直接使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     *
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     *
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     *
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        // 定义头部字段常量
        final String X_FORWARDED_FOR = "x-forwarded-for";
        final String PROXY_CLIENT_IP = "Proxy-Client-IP";
        final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
        final String UNKNOWN_IP = "unknown";
        final String LOCAL_IP = "127.0.0.1";
        final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";
        final int IP_LEN = 15; // 假设IP地址最大长度为15

        // 尝试从头部字段获取IP地址
        String ipAddress = request.getHeader(X_FORWARDED_FOR);
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(PROXY_CLIENT_IP);
        }
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(WL_PROXY_CLIENT_IP);
        }

        // 如果没有通过头部字段获取到IP地址，尝试从请求中获取
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (LOCAL_IP.equals(ipAddress) || LOCAL_IPV6.equals(ipAddress)) {
                try {
                    // 获取本机IP地址
                    InetAddress inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    // 记录错误日志
                    log.error("Unable to get local host IP address", e);
                }
            }
        }

        // 处理通过多个代理的情况，提取第一个IP地址
        if (ipAddress != null && ipAddress.length() > IP_LEN) {
            int index = ipAddress.indexOf(",");
            if (index > 0) {
                ipAddress = ipAddress.substring(0, index);
            }
        }

        return ipAddress;
    }
}
